package com.ww.springboot.mybatis.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ww.springboot.mybatis.dto.CommonDTO;
import com.ww.springboot.mybatis.mapper.CommonMapper;
import com.ww.springboot.mybatis.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2023-11-03 09:44
 */
@RequestMapping("read")
@RestController
public class ReadDataSourceController {

    @Autowired
    private CommonMapper commonMapper;


    @GetMapping("read")
    public String read(Long id) {
        List<CommonDTO> commonDTOS = new ArrayList<>();
        int i = 1;
        while (true) {
            List<CommonDTO> list = commonMapper.read(id);
            if (ObjectUtil.isEmpty(list)) {
                break;
            }
            list.sort(Comparator.comparing(CommonDTO::getId));
            id = list.get(list.size() - 1).getId();
            this.deal(list);
            commonDTOS.addAll(list);
            i++;
            System.out.println(i);
        }
        EasyExcel.write(new File("C:\\Users\\ZH500\\桌面\\test\\sp.xlsx"), CommonDTO.class).sheet("xxx").doWrite(commonDTOS);
        System.out.println("结束");
        return "";
    }

    private void deal(List<CommonDTO> list) {
        list.forEach(dto -> {
            try {
                String orderDetailJson = dto.getOrderEscrowJson();

                JSONObject jsonObject = JSON.parseObject(orderDetailJson);
                String data = jsonObject.getString("data");
                JSONObject jsonObject1 = JSON.parseObject(data);
                String response = jsonObject1.getString("response");
                JSONObject jsonObject2 = JSON.parseObject(response);
                String orderIncome = jsonObject2.getString("order_income");
                JSONObject jsonObject3 = JSON.parseObject(orderIncome);
                String buyer_paid_shipping_fee = jsonObject3.getString("buyer_paid_shipping_fee");
                String estimated_shipping_fee = jsonObject3.getString("estimated_shipping_fee");
                String shopee_shipping_rebate = jsonObject3.getString("shopee_shipping_rebate");
                dto.setBuyerPaidShippingFee(buyer_paid_shipping_fee);
                dto.setEstimatedShippingFee(estimated_shipping_fee);
                dto.setShopeeShippingRebate(shopee_shipping_rebate);
                dto.setOrderEscrowJson(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
